package com.io.service.impl;

import com.io.service.ThreadService;
import com.io.utils.ThreadPollUtil;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Service;

import java.util.HashMap;
import java.util.Map;
import java.util.concurrent.CountDownLatch;
import java.util.concurrent.ThreadPoolExecutor;


@Service
@Slf4j
public class ThreadServiceImpl  implements ThreadService {


    /**
     * 多线程
     */
    @Override
    public Map selectAllCountByThread() throws InterruptedException {
        log.info("开始执行多线程");

        Map map = new HashMap();
//        1.创建计数器
        CountDownLatch latch = new CountDownLatch(3);

//        2.通过线程池执行三个任务
        ThreadPoolExecutor executor = ThreadPollUtil.executor;

        executor.submit(new Runnable() {
            @Override
            public void run() {
                map.put("","");
//                计数器减一
                latch.countDown();
            }
        });
        executor.submit(new Runnable() {
            @Override
            public void run() {
                try {
                    map.put("","");
                }catch (Exception e){

                }finally {

                    latch.countDown();
                }

            }
        });
        executor.submit(new Runnable() {
            @Override
            public void run() {
                map.put("","");

                latch.countDown();
            }
        });

//        3.让主线程等待
        latch.await();

        return map;
    }

}
